import axios from 'axios'
import requestUrl from './api.js'
import router from '../router/index.js'
import { Message,Loading } from 'element-ui'
let requestOption = {};//保存上次请求的参数
var use_token = false;//是否需要使用第二token
console.log('requestUrl:' + requestUrl.baseUrl)
const request = axios.create({
  baseURL: requestUrl.baseUrl,
  timeout: 1000 * 12,
  method: 'GET',
})

// 设置post请求头
request.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded;charset=UTF-8'
request.defaults.headers.get['Content-Type'] = 'Access-Control-Allow-Origin'

// 请求前拦截器
let myLoad = null;
request.interceptors.request.use(
  (config) => {
    //配置模拟数据
    // if (config.mock && config.mock === true) {
    //     config.baseURL = ""
    // }
    myLoad = Loading.service({
      text:'加载中...'
    });
    const myToken = localStorage.getItem('token');
    const refreshToken = localStorage.getItem('refreshToken');
    config.headers = {
      'Content-Type': 'application/json',
      'token':use_token?refreshToken:myToken
    }
    return config
  },
  (error) => {
    //请求错误时做些事
    return Promise.reject(error)
  }
)

// 请求后拦截
request.interceptors.response.use(
  (response) => {
    myLoad.close();
    const header = response.headers;
    const obj = response.data
    //跳转登录
    // if(header['IW-Author-token']){
    //   localStorage.setItem('token',header['IW-Author-token'])
    // }
    if(obj.success===false){
       Message({
        message: obj.msg,
        type:'error'
      })
      // return obj;
    }else{
      if(obj.data){
        if(obj.data.refreshToken){
          localStorage.setItem('refreshToken',obj.data.refreshToken);
        }
        if(obj.data.token){
          localStorage.setItem('token',obj.data.token);
        }
      }
    }
    switch (obj.status) {
      case 10002:
        router.push({ path: 'login' })
        break;
        case 10402:
          if(!use_token){
            use_token = true
            myRequest(requestOption)
          }else{
            use_token = false;
            router.push({ path: 'login' })
          }
          break;
      default:
        break;
    }
    
    return obj
  },
  (error) => {
    myLoad.close();
    Message({
      message: error.message,
      type:'error'
    })
    return Promise.reject(error)
  }
)
export const myRequest = (options = {})=>{
  requestOption = options;
  return request({
    method: options.method,
    data: options.params,
    url: (function() {
      const URL = options.url
      let _url = ''
      if (typeof URL === 'object' && URL.params) {
        _url = requestUrl[URL.name]
        let _params = URL.params
        let ind = 0
        for (const key in _params) {
          if (options.inUrl) {
            _url = _url.replace(/\${[a-zA-Z0-9]+}/, _params[key])
          } else {
            _url += (ind > 0 ? '&' : '?') + key + '=' + _params[key]
          }
          ind++
        }
        return _url
      } else {
        _url = requestUrl[URL]
        return _url
      }
    })(),
    //查询字符串参数
    // params:options.params,
    
  })
}
